"""照片接口爬取"""

import csv
import json
import requests
import pandas as pd
from mysql_conn.mysql_conn import MysqlConn
from setting import BASE_DIR


class Photos():

    address = 'https://face.scu.edu.cn'

    def __init__(self, appid, appsecret):
        self.get_access_token(appid, appsecret)
        # self.refresh_token(appid, appsecret)

    def get_photo_by_xgh(self, xgh):
        url = '/api/photo/get-one'
        headers = {
            "Content-Type": "application/x-www-form-urlencoded",
        }
        body = {
            "access_token": self.token,
            "xgh": xgh
        }
        res = requests.post(Photos.address + url, data=body, headers=headers)
        data = json.loads(res.text)['d'].get('images')
        print(data)
        pass

    def get_access_token(self, appid, appsecret):
        url = Photos.address + '/api/third/get-token?appid={}&appsecret={}'.format(appid, appsecret)
        res = requests.get(url, )
        if res.status_code == 200:
            access_token = res.json().get('d').get('access_token')
            print(access_token)
            self.token = access_token
        else:
            print(res.text)
            raise Exception()

    def refresh_token(self, appid, appsecret):
        url = Photos.address + '/api/third/refresh-token?appid={}&appsecret={}'.format(appid, appsecret)
        res = requests.get(url, )
        if res.status_code == 200:
            access_token = res.json().get('d').get('access_token')
            print(access_token)
            self.token = access_token
            return access_token
        else:
            print(res.text)
            raise Exception()

    # 批量获取用户照片
    def get_photos(self, page):
        """获指定页码的照片 100条"""
        url = '/api/photo/get-list'
        headers = {
            "Content-Type": "application/x-www-form-urlencoded",
        }
        body = {
            "access_token": self.token,
            'page': page,
            'page_size': 100,
            # 'time': ''
        }
        res = requests.post(Photos.address + url, data=body, headers=headers)
        print(res.json())
        data = json.loads(res.text)['d'].get('data')
        return data

    def get_school_in_photos(self):
        """获取在校人员照片"""
        url = '/api/photo/school-info'
        headers = {
            "Content-Type": "application/x-www-form-urlencoded",
        }
        body = {
            "access_token": self.token,
            "timestamp": ''
        }
        res = requests.post(Photos.address + url, data=body, headers=headers)
        data = json.loads(res.text)['d'].get('list')
        print(data)
        pass

    def write_all_to_csv(self,):
        """获取所有照片到本地csv"""
        with open('photos.csv', 'a+', encoding='utf-8', newline="") as f:
            writer = csv.writer(f)
            writer.writerow(['xgh', 'photo'])
            num = 0
            while True:
                print(num)
                try:
                    data = self.get_photos(num)
                    if data:
                        rows = []
                        for item in data:
                            rows.append([item.get('xgh'), item.get('photo')])
                        writer.writerows(rows)
                    else:
                        break
                    num += 1
                except:
                    print(f'异常： {num}')

    @staticmethod
    def csv_to_mysql(file_path, table_name):
        mysql1 = MysqlConn("10.3.1.154", 'root', 'S0beydbaAt2o2o', 'human_resources', 3307)
        df_data = pd.read_csv(file_path)
        mysql1.xls_to_mysql(df_data, table_name)


if __name__ == '__main__':
    appid = '200200707165400485'
    appsecret = '6f9lhnti8dzu808bakea7su15i71jh7n'
    p = Photos(appid, appsecret)
    # p.write_all_to_csv()
    p.get_photos(0)
    # p.get_school_in_photos()
    # p.get_photo_by_xgh('2020141210122')
    # Photos.csv_to_mysql('photos.csv', 'photoes')
    pass